import { Cartesian3, Viewer, WebMapTileServiceImageryProvider, Math, Cartographic, EllipsoidGeodesic, Ellipsoid } from 'cesium'
type TMapType = 'vec' | 'cva' | 'img' | 'cia' | 'ter' | 'cta' | 'ibo' | 'eva' | 'eia'
/**
 * 为cesium添加天地图的底图
 * @param viewer
 * @param layer
 * vec：矢量底图、cva：矢量标注、img：影像底图、cia：影像标注
 * ter：地形晕渲、cta：地形标注、eva：矢量英文标注、eia：影像英文标注
 */
export function addTMap (viewer: Viewer, layer: TMapType) {
  // 添加天地图影像注记底图 d434002ddef854e56c24ce68e885a55b
  const tMapImagery = new WebMapTileServiceImageryProvider({
    url: `https://t0.tianditu.gov.cn/${layer}_w/wmts?tk=6460c0045a3ab09f33e9f40c2d1d36a4`,
    layer,
    style: 'default',
    tileMatrixSetID: 'w',
    format: 'tiles',
    maximumLevel: 18
  })
  viewer.imageryLayers.addImageryProvider(tMapImagery)
}

/**
 * 计算一系列位置的中心点，并使用 Cesium 地图跳转到该位置。
 *
 * @param {Array} positions - 包含经纬度和高度的数组。
 * @returns {void}
 */
export const jump = (positions: number[][]) => {
  let arr: number[] = []
  let arr2: number[] = []
  for (const k of positions) {
    const position = Cartesian3.fromDegrees(k[0], k[1], k[2])
    const cartesian3 = new Cartesian3(position.x, position.y, position.z)
    const cartographic = Ellipsoid.WGS84.cartesianToCartographic(cartesian3)
    arr.push(Math.toDegrees(cartographic.latitude))
    arr2.push(Math.toDegrees(cartographic.longitude))
  }
  arr = arr.sort()
  arr2 = arr2.sort()
  const startLat = (arr[0] + arr[arr.length - 1]) / 2
  const endLat = (arr2[0] + arr2[arr2.length - 1]) / 2
  const startLatitude = startLat
  const startLongitude = endLat
  const endLatitude = arr[0]
  const endLongitude = arr2[0]
  const startCartographic = Cartographic.fromDegrees(startLongitude, startLatitude)
  const endCartographic = Cartographic.fromDegrees(endLongitude, endLatitude)
  /** 根据经纬度计算出距离**/
  const geodesic = new EllipsoidGeodesic()
  geodesic.setEndPoints(startCartographic, endCartographic)
  const distance = geodesic.surfaceDistance
  const position = Cartesian3.fromDegrees(endLat, startLat, distance * 4)
  return position
}

/**
 * 计算经纬度
 * @param {Cesium.Cartesian3} cartesian - 笛卡尔坐标
 * @returns {{Lon: number, Lat: number}} - 经纬度
 */
export const getLonLatByCartesian = (cartesian: Cartesian3): { Lon: number; Lat: number } => {
  const cartographic = Cartographic.fromCartesian(cartesian)
  const Lon = Math.toDegrees(cartographic.longitude)
  const Lat = Math.toDegrees(cartographic.latitude)
  return { Lon, Lat }
}
